package org.csu.mybigpro.controller;

import jakarta.annotation.Resource;
import org.csu.mybigpro.DTO.SurveyUpdateDTO;
import org.csu.mybigpro.common.CommonResponse;
import org.csu.mybigpro.domain.Assignment;
import org.csu.mybigpro.domain.Survey;
import org.csu.mybigpro.properties.AssignmentProperties;
import org.csu.mybigpro.properties.SurveyProperties;
import org.csu.mybigpro.service.SurveyService;
import org.csu.mybigpro.util.MinioUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/surveys")
public class SurveyController {
    @Autowired
    private SurveyService surveyService;

    @Resource
    private SurveyProperties surveyProperties;

    @Autowired
    private MinioUtil minioUtil;

    @PostMapping("/publish")
    public CommonResponse<String> publishSurvey(
            @RequestParam("title") String title,
            @RequestParam("status") String status,
            @RequestParam("creator") String creator,
            @RequestParam(value = "createdAt", required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime createdAt,
            @RequestParam(value = "file", required = false) MultipartFile file
    ) {
        String filePath = null;

        try {
            if (file != null && !file.isEmpty()) {
                // 用MinioUtil上传文件，返回文件URL
                filePath = minioUtil.uploadFile(file);
            }
        } catch (Exception e) {
            return CommonResponse.createForError(400, "文件上传失败: " + e.getMessage());
        }

        Survey survey = new Survey();
        survey.setTitle(title);
        survey.setStatus(status);
        survey.setCreator(creator);
        // 如果前端没传创建时间，默认用当前时间
        survey.setCreatedAt(createdAt == null ? LocalDateTime.now() : createdAt);
        survey.setFilePath(filePath);

        surveyService.saveSurvey(survey);

        Map<String, Object> data = new HashMap<>();
        data.put("survey", survey);

        return CommonResponse.createForSuccess("问卷调查发布成功", data.toString());
    }

    // 查询所有问卷
    @GetMapping("/list")
    public CommonResponse<List<Survey>> getAllSurveys() {
        List<Survey> surveys = surveyService.getAllSurveys();
        return CommonResponse.createForSuccess(surveys);
    }

    // 根据id查询问卷
    @GetMapping("/{id}")
    public CommonResponse<Survey> getSurveyById(@PathVariable Long id) {
        Survey survey = surveyService.getSurveyById(id);
        if (survey == null) {
            return CommonResponse.createForError(404, "问卷不存在");
        }
        return CommonResponse.createForSuccess(survey);
    }

    @GetMapping("/title/{title}")
    public CommonResponse<List<Survey>> getSurveyByTitle(@PathVariable String title) {
        List<Survey> surveys = surveyService.getSurveyByTitle(title);
        if (surveys == null || surveys.isEmpty()) {
            return CommonResponse.createForError(404, "问卷不存在");
        }
        return CommonResponse.createForSuccess(surveys);
    }


    // 修改问卷（传整个Survey对象）
    @PutMapping("/update")
    public CommonResponse<String> updateSurvey(
            @ModelAttribute SurveyUpdateDTO dto,
            @RequestParam(value = "file", required = false) MultipartFile file
    ) {
        Survey existing = surveyService.getSurveyById(dto.getId());
        if (existing == null) {
            return CommonResponse.createForError(404, "问卷不存在");
        }

        if (dto.getTitle() != null) existing.setTitle(dto.getTitle());
        if (dto.getStatus() != null) existing.setStatus(dto.getStatus());
        if (dto.getCreator() != null) existing.setCreator(dto.getCreator());
        if (dto.getCreatedAt() != null) existing.setCreatedAt(dto.getCreatedAt());

        if (file != null && !file.isEmpty()) {
            try {
                String url = minioUtil.uploadFile(file);
                existing.setFilePath(url);
            } catch (Exception e) {
                return CommonResponse.createForError(500, "文件上传失败：" + e.getMessage());
            }
        }

        surveyService.updateSurvey(existing);
        return CommonResponse.createForSuccess("问卷更新成功");
    }



    // 删除问卷
    @DeleteMapping("/delete/{id}")
    public CommonResponse<String> deleteSurvey(@PathVariable Long id) {
        boolean success = surveyService.deleteSurveyById(id);
        if (success) {
            return CommonResponse.createForSuccess("问卷删除成功");
        } else {
            return CommonResponse.createForError(400, "问卷删除失败");
        }
    }
}
